package com.xiaowen.projectDataTitle.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xiaowen.projectData.entity.ProjectData;
import com.xiaowen.projectData.service.ProjectDataService;
import com.xiaowen.projectDataTitle.dto.ProjectDataColumn;
import com.xiaowen.projectDataTitle.dto.ProjectDataTitleDTO;
import com.xiaowen.projectDataTitle.service.ProjectDataTitleService;
import com.xiaowen.projectDataTitle.entity.ProjectDataTitle;
import com.xiaowen.projectDataTitle.mapper.ProjectDataTitleMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowen.redis.RedisKeys;
import com.xiaowen.redis.RedisUtils;
import com.xiaowen.tool.JsonUtils;
import com.xiaowen.tool.exception.XwException;
import com.xiaowen.tool.excle.NoModleDataListener;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.xiaowen.redis.RedisUtils.NOT_EXPIRE;

/**
 * <p>
 * 项目数据列表 服务实现类
 * </p>
 *
 * @author yf-wenhao
 * @since 2024-09-30
 */
@Service
public class ProjectDataTitleServiceImpl extends ServiceImpl<ProjectDataTitleMapper, ProjectDataTitle> implements ProjectDataTitleService {

    @Autowired
    private ProjectDataTitleMapper projectDataTitleMapper;

    @Autowired
    private ProjectDataService projectDataService;

    @Override
    public List<String> getHeadList(MultipartFile importFile, Integer projectId) {
        //读取excel数据
        NoModleDataListener noModleDataListener = new NoModleDataListener();
        try {
            EasyExcel.read(importFile.getInputStream(), noModleDataListener).headRowNumber(0).sheet().doRead();
        } catch (Exception e){
            log.error("获取文件错误：{}",e);
            return null;
        }
        List<List<String>> headList = noModleDataListener.getHeadList();
        List<String> titleList = headList.get(0);
        List<Map<String, Object>> dataList = noModleDataListener.getDataList();
        if (CollectionUtils.isNotEmpty(titleList) && CollectionUtils.isNotEmpty(dataList)){
            Date now = new Date();
            //存headlist到项目表头表
            ProjectDataTitle projectDataTitle = new ProjectDataTitle();
            projectDataTitle.setProjectId(projectId);
            projectDataTitle.setCreateTime(now);
            projectDataTitle.setProjectDataTitle(JsonUtils.toJson(titleList));
            deleteProjectDataTitleByProjectId(projectId);
            addProjectDataTitle(projectDataTitle);

            //处理数据，存数据表
            projectDataService.deleteProjectDataByProjectId(projectId);
            List<ProjectData> projectDataList = Lists.newArrayList();
            dataList.forEach(data->{
                ProjectData projectData = new ProjectData();
                projectData.setProjectId(projectId);
                projectData.setCreateTime(now);
                projectData.setDataValExt(JsonUtils.toJson(data));
                projectDataList.add(projectData);
            });
            projectDataService.batchAddProjectData(projectDataList);
        }else {
            throw new XwException(500,"数据解析错误,请检查文件");
        }
        return headList.get(0);
    }

    @Override
    public void setUpProjectDataColumn(ProjectDataColumn projectDataColumn) {
        ProjectDataTitleDTO projectDataTitleDTO = queryProjectDataTitleByProjectId(projectDataColumn.getProjectId());
        if (ObjectUtil.isEmpty(projectDataTitleDTO)){
            throw new XwException(500,"项目数据标题不存在");
        }

        List<ProjectData> projectDataList = projectDataService.queryProjectDataListByProjectId(projectDataColumn.getProjectId());
        if (CollectionUtils.isEmpty(projectDataList)){
            throw new XwException(500,"项目数据不存在");
        }
        Date now = new Date();
        //更新标题
        projectDataTitleDTO.setIdColumn(projectDataColumn.getIdColumn());
        projectDataTitleDTO.setOriginalWordColumn(projectDataColumn.getOriginalWordColumn());
        projectDataTitleDTO.setUpdateTime(now);
        ProjectDataTitle projectDataTitle = new ProjectDataTitle();
        BeanUtils.copyProperties(projectDataTitleDTO, projectDataTitle);
        updateById(projectDataTitle);

        //更新数据
        projectDataList.forEach(projectData -> {
            Map dataValExtMap = JsonUtils.toBean(projectData.getDataValExt(), Map.class);
            if (ObjectUtil.isNotEmpty(dataValExtMap)){
                projectData.setIdVal(ObjectUtil.toString(dataValExtMap.get(projectDataColumn.getIdColumn())));
                projectData.setOriginalWordVal(ObjectUtil.toString(dataValExtMap.get(projectDataColumn.getOriginalWordColumn())));
                projectData.setUpdateTime(now);
                projectDataService.updateById(projectData);
            }
        });
    }


    @Override
    public void addProjectDataTitle(ProjectDataTitle projectDataTitle) {
        projectDataTitleMapper.insert(projectDataTitle);
    }

    @Override
    public void deleteProjectDataTitleByProjectId(Integer projectId) {
        ProjectDataTitle entity = new ProjectDataTitle();
        entity.setDeleteFlag(true);
        entity.setUpdateTime(new Date());
        QueryWrapper<ProjectDataTitle> queryWrapper = new QueryWrapper<>();
        ProjectDataTitle projectDataTitle = new ProjectDataTitle();
        projectDataTitle.setProjectId(projectId);
        projectDataTitle.setDeleteFlag(false);
        queryWrapper.setEntity(projectDataTitle);
        projectDataTitleMapper.update(entity, queryWrapper);
    }

    @Override
    public ProjectDataTitleDTO queryProjectDataTitleByProjectId(Integer projectId) {
        QueryWrapper<ProjectDataTitle> queryWrapper = new QueryWrapper<>();
        ProjectDataTitle projectDataTitle = new ProjectDataTitle();
        projectDataTitle.setProjectId(projectId);
        projectDataTitle.setDeleteFlag(false);
        queryWrapper.setEntity(projectDataTitle);
        List<ProjectDataTitle> projectDataTitleList = projectDataTitleMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(projectDataTitleList)){
            ProjectDataTitleDTO projectDataTitleDTO = new ProjectDataTitleDTO();
            BeanUtils.copyProperties(projectDataTitleList.get(0), projectDataTitleDTO);
            if (ObjectUtil.isNotEmpty(projectDataTitleDTO.getProjectDataTitle())){
                List<String> projectTitleList = JsonUtils.toBean(projectDataTitleDTO.getProjectDataTitle(), List.class);
                List<Map> columnList = projectTitleList.stream().map(v->{

                    Map<String, Object> columnMap = Maps.newHashMap();
                    columnMap.put("dataIndex", v);
                    columnMap.put("title", v);
                    columnMap.put("hideInSearch", true);
                    if (v.equals(projectDataTitleDTO.getIdColumn())){
                        columnMap.put("title", v+"（ID）");
                        //columnMap.put("hideInSearch", false);
                    }
                    if (v.equals(projectDataTitleDTO.getOriginalWordColumn())){
                        columnMap.put("title", v+"（原话）");
                        //columnMap.put("hideInSearch", false);
                    }
                    return columnMap;
                }).collect(Collectors.toList());
                projectDataTitleDTO.setProjectDataTitleList(columnList);
            }
            return projectDataTitleDTO;
        }
        return null;
    }


}
